package com.huika.renrench.control.my.fragment;

import java.text.DecimalFormat;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.lib.utils.MoneyShowTool;
import com.huika.lib.utils.StringTool;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseFra;
import com.huika.renrench.control.login.activity.LoginActivity;
import com.huika.renrench.control.more.activity.AsregardsActivity;
import com.huika.renrench.control.more.activity.FeedBackActivity;
import com.huika.renrench.control.my.account.AccountInfoActivity;
import com.huika.renrench.control.my.account.SetPayPwdActivity;
import com.huika.renrench.control.my.activity.AccountPropertyActivity;
import com.huika.renrench.control.my.activity.BorrowMoneyActivity;
import com.huika.renrench.control.my.activity.InvestmentManagementActivity;
import com.huika.renrench.control.my.activity.RechargeActivity;
import com.huika.renrench.control.my.activity.TransactionRecordActivity;
import com.huika.renrench.control.my.activity.UserInviteActivity;
import com.huika.renrench.control.my.activity.WithDrawActivity;
import com.huika.renrench.control.my.bank.activity.MyBankCardActivity;
import com.huika.renrench.control.my.certification.activity.CertificationActivity;
import com.huika.renrench.control.my.merchant.MerchantManageActivity;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.UserModel;
import com.huika.renrench.utils.LoginUtils;
import com.huika.renrench.utils.PhoneUtil;
import com.huika.renrench.utils.ShareUtils;
import com.huika.renrench.utils.WebNetUtils;
import com.huika.renrench.view.RoundImageView;
import com.huika.renrench.view.webview.BaseWebViewAct;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author yangyuan
 * @date：2015年6月2日,下午2:45:52
 * @describe:主页的我的Fragment
 */

public class MyFragment extends BaseFra {

	private RoundImageView img_user_pic;
	private TextView text_user_name;
	private TextView text_user_balance;
	private LinearLayout text_user_chong;// 充值
	private LinearLayout text_user_tixian;// 提现
	private TextView text_trading_account_assets;// 账户资产

	private LinearLayout lin_account_setting;//
	private LinearLayout lin_user_assets;//账户资产
	private LinearLayout lin_trading_record;//交易记录
	private LinearLayout lin_user_collect;//我关注的项目
	private LinearLayout lin_investment_management;//投资管理
	private LinearLayout lin_user_deliver;//我投递的项目
	private LinearLayout lin_user_invite;//我的邀请
	private LinearLayout lin_jie_feedback;//意见反馈
	private LinearLayout lin_regards_renrenc;//关于人人创

	private LinearLayout lin_zhanwei_01;
	private TextView text_zhanwei_02;

	private UserModel userBean;
	public DisplayImageOptions options;
	
	private Dialog dialog;

	@Override
	protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
		View root = inflater.inflate(R.layout.frag_my, container, false);
		return root;
	}

	@Override
	protected void initWidget(View parentView) {
		super.initWidget(parentView);
		img_user_pic = (RoundImageView) parentView.findViewById(R.id.img_user_pic);
		text_user_name = (TextView) parentView.findViewById(R.id.text_user_name);
		text_user_balance = (TextView) parentView.findViewById(R.id.text_user_balance);
		text_user_chong = (LinearLayout) parentView.findViewById(R.id.text_user_chong);
		text_user_tixian = (LinearLayout) parentView.findViewById(R.id.text_user_tixian);
		text_trading_account_assets = (TextView) parentView.findViewById(R.id.text_trading_account_assets);
		lin_account_setting = (LinearLayout) parentView.findViewById(R.id.lin_account_setting);
		lin_user_assets = (LinearLayout) parentView.findViewById(R.id.lin_user_assets);
		lin_trading_record = (LinearLayout) parentView.findViewById(R.id.lin_trading_record);
		lin_user_collect = (LinearLayout) parentView.findViewById(R.id.lin_user_collect);
		lin_investment_management = (LinearLayout) parentView.findViewById(R.id.lin_investment_management);
		lin_user_deliver = (LinearLayout) parentView.findViewById(R.id.lin_user_deliver);
		lin_user_invite = (LinearLayout) parentView.findViewById(R.id.lin_user_invite);
		lin_jie_feedback = (LinearLayout) parentView.findViewById(R.id.lin_jie_feedback);
		lin_regards_renrenc = (LinearLayout) parentView.findViewById(R.id.lin_regards_renrenc);
		
		lin_zhanwei_01 = (LinearLayout) parentView.findViewById(R.id.lin_zhanwei_01);
		text_zhanwei_02 = (TextView) parentView.findViewById(R.id.text_zhanwei_02);

		setOnclickListener();

		// 创建头像下载
		options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.img_user_pic).showImageForEmptyUri(R.drawable.img_user_pic)
				.showImageOnFail(R.drawable.img_user_pic).cacheInMemory(true)// 开启内存缓存
				.cacheOnDisk(true) // 开启硬盘缓存
				.resetViewBeforeLoading(false).build();
	}

	/** 控件添加监听器 */
	private void setOnclickListener() {
		lin_account_setting.setOnClickListener(this);
		text_user_chong.setOnClickListener(this);
		text_user_tixian.setOnClickListener(this);
		lin_user_assets.setOnClickListener(this);
		lin_trading_record.setOnClickListener(this);
		lin_user_collect.setOnClickListener(this);
		lin_investment_management.setOnClickListener(this);
		lin_user_deliver.setOnClickListener(this);
		lin_user_invite.setOnClickListener(this);
		lin_jie_feedback.setOnClickListener(this);
		lin_regards_renrenc.setOnClickListener(this);
	}

	@Override
	public void onResume() {// 持续更新ui
		super.onResume();
		if (LoginUtils.isLogin()) {// 判断是否登录
			getResponse();
			getUpdateUserDatas();
			lin_zhanwei_01.setVisibility(View.VISIBLE);
			text_zhanwei_02.setVisibility(View.GONE);
		} else {
			img_user_pic.setImageResource(R.drawable.img_user_pic);
			text_trading_account_assets.setText("");
			lin_zhanwei_01.setVisibility(View.GONE);
			text_zhanwei_02.setVisibility(View.VISIBLE); 
		}
	}

	private void getResponse() {
		userBean = GlobalApp.getInstance().getUserModel();
		
		if (StringTool.isEmpty(userBean.getAccount())) {
			text_user_name.setText(PhoneUtil.TelPhoneStr(userBean.getPhone()));
		}else {
			text_user_name.setText(userBean.getAccount());
		}
		
		text_user_balance.setText("可用余额: " + MoneyShowTool.twolastDF(userBean.getBalance()) + "元");
		text_trading_account_assets.setText("¥" + MoneyShowTool.twolastDF(userBean.getAmountTotal()));
		 ImageLoader.getInstance().displayImage(userBean.getHeadImg(),
		 img_user_pic, options);
	}

	@Override
	protected void widgetClick(View v) {
		if (!LoginUtils.isLogin()) {
			showActivity(getActivity(), LoginActivity.class);
			return;
		}
		super.widgetClick(v); 
		switch (v.getId()) {
		case R.id.lin_account_setting:// 设置信息
			showActivity(getActivity(), AccountInfoActivity.class);
			break;
		case R.id.text_user_chong:
					if(TextUtils.isEmpty(GlobalApp.userModel.getIdCard()) ||
							TextUtils.isEmpty(GlobalApp.userModel.getRealName())) {
						warning();
						return;
					}
					showActivity(getActivity(), RechargeActivity.class);
			break;
		case R.id.text_user_tixian://提现
				if(TextUtils.isEmpty(GlobalApp.userModel.getIdCard()) ||
						TextUtils.isEmpty(GlobalApp.userModel.getRealName())) {
					warning();
					return;
				} else if(GlobalApp.userModel.getIsSetPayPwd() == 0) { 
					dialog = MMAlert.createShowCenterDialog(getActivity(), "温馨提示", "您未设置交易密码，请先设置", "忽略", "前往设置", null, new OnClickListener() {
						@Override
						public void onClick(View v) { 
							showActivity(getActivity(), SetPayPwdActivity.class);
						}
					});
					dialog.show();
					return;
				} 
			showActivity(getActivity(), WithDrawActivity.class);
			break;
		case R.id.lin_user_assets:
			showActivity(getActivity(), AccountPropertyActivity.class);
			break;
		case R.id.lin_trading_record:
			// showToastMsg("交易记录");//交易记录入口
			showActivity(getActivity(), TransactionRecordActivity.class);
			break;
		case R.id.lin_user_collect:// 我的关注
			showToastMsg("我的关注");
			break; 
		case R.id.lin_investment_management:// 投资管理
			showActivity(getActivity(), InvestmentManagementActivity.class);
			break;
		case R.id.lin_user_deliver:// 我投递的项目
			showToastMsg("我投递的项目");
			break;
		case R.id.lin_user_invite:// 我的邀请
			showActivity(getActivity(), UserInviteActivity.class);
			break;
		case R.id.lin_jie_feedback:// 意见反馈
			startActivity(new Intent(getActivity(), FeedBackActivity.class)); 
			break;
		case R.id.lin_regards_renrenc:// 关于人人创
			startActivity(new Intent(getActivity(), AsregardsActivity.class));
			break;
		}
	}
	
	private void warning() {
		dialog = MMAlert.createShowCenterDialog(getActivity(), "温馨提示", "您还没有实名认证，请先进行实名认证", "忽略", "立即前往", null, new OnClickListener() {
			@Override
			public void onClick(View v) {
				showActivity(getActivity(), CertificationActivity.class);
			}
		});
		dialog.show();
	}

	
	/***
	 * 获取网络数据,刷新用户信息
	 * @author yy
	 * @date  2015年4月7日
	 */
	private void getUpdateUserDatas(){
		executeUpdateUserInfoList();
	}
	
	/** 获取网络数据,刷新用户信息*/
	private void executeUpdateUserInfoList(){
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserId());//userId
		FormResultRequest<UserModel> request = new FormResultRequest<UserModel>(UrlConstants.FINDUSERBYUSERID, getUpdateUserResp, this, new TypeToken<RequestResult<UserModel>>() {}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	private Listener<RequestResult<UserModel>> getUpdateUserResp=new Listener<RequestResult<UserModel>>() {
		
		@Override
		public void onResponse(RequestResult<UserModel> result) {
			
			if (result.flag == 1) {
				if (result != null && result.getRs() != null) {
					UserModel bean = result.getRs();
					if (userBean==null) {
						userBean = bean;
					}
						userBean.setUserId(bean.getUserId());
						userBean.setAmountTotal(bean.getAmountTotal());
						userBean.setRealName(bean.getRealName());
						userBean.setIdCard(bean.getIdCard());
						userBean.setPhone(bean.getPhone());
						userBean.setIsSetPayPwd(bean.getIsSetPayPwd());
						userBean.setAccount(bean.getAccount());
						userBean.setHeadImg(bean.getHeadImg());
						userBean.setNickName(bean.getNickName());
						userBean.setLoanAmount(bean.getLoanAmount());
						userBean.setBalance(bean.getBalance());
						userBean.setYearRate(bean.getYearRate()); 
						userBean.setUserType(bean.getUserType()); 
						userBean.setHasProject(bean.getHasProject());
						userBean.setProjectId(bean.getProjectId());
						userBean.setBigImgUrl(bean.getBigImgUrl());
					GlobalApp.userModel = userBean;
					getResponse();
				}
			} else {
//				showToastMsg(result.msg);
			}
			dismissLoadingDialog();
			if (mOverlayLayout != null)
				hideOverLay();
		}
	};
	
}
